//
//  NSString+QTZ.m
//  QTZ
//
//  Created by ski on 2017/7/5.
//  Copyright © 2017年 ski. All rights reserved.
//

#import "NSString+QTZ.h"
#import <CommonCrypto/CommonDigest.h>
#include <ctype.h>

@implementation NSString (QTZ)

- (NSString *)addParamsToUrlFromDictionary:(NSDictionary *)params
{
    NSMutableString *_add = nil;
    if (NSNotFound != [self rangeOfString:@"?"].location) {
        _add = [NSMutableString stringWithString:@"&"];
    }else {
        _add = [NSMutableString stringWithString:@"?"];
    }
    for (NSString* key in [params allKeys]) {
        NSString *value = [params objectForKey:key];
        if (value && [value isKindOfClass:[NSString class]] && 0 < [value length]) {
            [_add appendFormat:@"%@=%@&",[key urlencode],[value urlencode]];
        }
    }
    NSInteger position = self.length;
    NSRange range = [self rangeOfString:@"#"];
    if (range.length > 0) {
        position = range.location;
    }
    NSMutableString *string = [self mutableCopy];
    [string insertString:[_add substringToIndex:[_add length] - 1] atIndex:position];
    return string;
}

- (NSString *)urldecode {
    return [[self stringByReplacingOccurrencesOfString:@"+" withString:@" "] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
}

- (NSString *)urlencode {
    NSString *charactersToEscape = @":/?&=;+!@#$()',*";
    NSCharacterSet *allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];
    return [self stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
}

- (NSString *)MD5
{
    if(self == nil || [self length] == 0)
        return nil;
    
    const char* str = [self UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), result);
    
    NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH*2];
    for(int i = 0; i<CC_MD5_DIGEST_LENGTH; i++) {
        [ret appendFormat:@"%02x",result[i]];
    }
    return ret;
}

- (NSString *)trim
{
    if( self == nil || [self isKindOfClass:[NSNull class]] ) {
        return nil;
    }
    
    
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

- (CGSize)sizeWithUIFont:(UIFont *)font forWidth:(CGFloat)width
{
    NSDictionary *attribute = @{NSFontAttributeName:font};
    CGSize size = [self sizeWithUIAttribute:attribute forWidth:width];
    return size;
}

- (CGSize)sizeWithUIAttribute:(NSDictionary *)attribute forWidth:(CGFloat)width
{
    CGSize size = [self boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
    
    return size;
}

- (NSString *)stringFromDataWithFormatter:(NSDateFormatter *)formatter
{
    NSString *result = nil;
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[self integerValue]];
    
    if (date && formatter) {
        
        result = [formatter stringFromDate:date];
    }
    
    return result;
}

+ (NSString *)stringWithDate:(NSString *)date
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSDate *dateStr = [NSDate dateWithTimeIntervalSince1970:[date doubleValue] / 1000];
    NSString *transformStr = [formatter stringFromDate:dateStr];
    return transformStr;
}

+ (NSString *)stringWithTime:(NSString *)time
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[time doubleValue]];
    NSString *transform = [formatter stringFromDate:date];
    return transform;
}

//金额加,
+ (NSString *)countNumAndChangeformat:(NSString *)num
{
    if (!num) return nil;
    //整数
    NSString* str11;
    //小数点之后的数字
    NSString* str22;
    
    if ([num containsString:@"."]) {
        NSArray* array = [num componentsSeparatedByString:@"."];
        
        str11 = array[0];
        str22 = array[1];
        
    }else{
        
        str11 = num;
    }
    
    
    int count = 0;
    long long int a = str11.longLongValue;
    while (a != 0)
    {
        count++;
        a /= 10;
    }
    NSMutableString *string = [NSMutableString stringWithString:str11];
    NSMutableString *newstring = [NSMutableString string];
    while (count > 3) {
        count -= 3;
        NSRange rang = NSMakeRange(string.length - 3, 3);
        NSString *str = [string substringWithRange:rang];
        [newstring insertString:str atIndex:0];
        [newstring insertString:@"," atIndex:0];
        [string deleteCharactersInRange:rang];
    }
    [newstring insertString:string atIndex:0];
    
    if ([num containsString:@"."]) {
        //包含小数点
        //返回的数字
        NSString* str33;
        
        if (str22.length>0) {
            //小数点后面有数字
            
            str33 = [NSString stringWithFormat:@"%@.%@",newstring,str22];
        }else{
            //没有数字
            str33 = [NSString stringWithFormat:@"%@",newstring];
        }
        return str33;
        
    }else{
        
        //不包含小数点
        return newstring;
    }
    
}

+ (NSString *)replaceStringWithAsterisk:(NSString *)originalStr startLocation:(NSInteger)startLocation lenght:(NSInteger)lenght
{
    if (startLocation + lenght > originalStr.length) {
        return originalStr;
    }
    NSString *newStr = originalStr;
    for (int i = 0; i < lenght; i++) {
        NSRange range = NSMakeRange(startLocation, 1);
        newStr = [newStr stringByReplacingCharactersInRange:range withString:@"*"];
        startLocation ++;
    }
    return newStr;
}

+ (NSString *)getNewBankNumWitOldBankNum:(NSString *)bankNum
{
    NSMutableString *mutableStr;
    if (bankNum.length) {
        mutableStr = [NSMutableString stringWithString:bankNum];
        for (int i = 0 ; i < mutableStr.length; i ++) {
            if (i>3&&i<mutableStr.length - 3) {
                [mutableStr replaceCharactersInRange:NSMakeRange(i, 1) withString:@"*"];
            }
        }
        NSString *text = mutableStr;
        NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];
        text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
        NSString *newString = @"";
        while (text.length > 0) {
            NSString *subString = [text substringToIndex:MIN(text.length, 4)];
            newString = [newString stringByAppendingString:subString];
            if (subString.length == 4) {
                newString = [newString stringByAppendingString:@" "];
            }
            text = [text substringFromIndex:MIN(text.length, 4)];
        }
        newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];
        return newString;
    }
    return bankNum;
    
}

+ (NSString *)projectNameWithType:(NSString *)type businessType:(NSString *)businessType name:(NSString *)name
{
    NSString *projectName;
    if ([type isEqualToString:@"16"]) {//新手标
        projectName = @"新手标";
    } else if ([type isEqualToString:@"14"]) {
        if ([businessType isEqualToString:@"1"]) {//车易宝
            projectName = @"车易宝";
        } else if ([businessType isEqualToString:@"2"]) {//企易融
            projectName = @"企易融";
        } else if ([businessType isEqualToString:@"3"]) {//惠民宝
            projectName = @"惠民宝";
        } else {
            if ([name rangeOfString:@"周转借款" ].location == NSNotFound && [name rangeOfString:@"个人消费" ].location == NSNotFound) {//企易融
                projectName = @"企易融";
            }else {//惠民宝
                projectName = @"惠民宝";
            }
        }
    }
    return projectName;
}

+ (NSString *)jsonStringWithDict:(NSDictionary *)dict {
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return mutStr;
    
}

@end
